package com.jt808.decode.utils;

import com.jt808.decode.model.Jt808Message;
import com.jt808.decode.model.TerminalAuthInfo;
import io.netty.buffer.ByteBuf;

/**
 * Terminal authentication
 * @author HyoJung
 * @date 20230303
 */
public class Message0102Parser {
    /**
     * Terminal authentication
     * @param msg
     * @param msgBody
     * @return
     */
    public static TerminalAuthInfo parse(Jt808Message msg, ByteBuf msgBody){
        TerminalAuthInfo terminalAuthInfo;
        if (msg.getVersionFlag() == 1) {
            terminalAuthInfo = parseAuthInfo2019(msgBody);
        } else {
            terminalAuthInfo = parseAuthInfo(msgBody);
        }
        terminalAuthInfo.setTerminalNum(msg.getPhoneNumber());
        terminalAuthInfo.setHexMsgId(NumberUtil.formatMessageId(msg.getMsgId()));
        terminalAuthInfo.setMsgFlowId(msg.getMsgFlowId());
        return terminalAuthInfo;
    }

    /**
     * Decode authentication code
     *
     * @param msgBodyBuf
     */
    private static TerminalAuthInfo parseAuthInfo(ByteBuf msgBodyBuf) {
        String authCode = CommonUtil.readGbkString(msgBodyBuf, msgBodyBuf.readableBytes());
        TerminalAuthInfo terminalAuthInfo = new TerminalAuthInfo();
        terminalAuthInfo.setAuthCode(authCode);
        return terminalAuthInfo;
    }

    /**
     * Decode authentication code for JT808-2019
     *
     * @param msgBodyBuf
     */
    private static TerminalAuthInfo parseAuthInfo2019(ByteBuf msgBodyBuf) {
        //Authentication code length
        int authCodeLen = msgBodyBuf.readByte();
        //Authentication code content
        String authCode = CommonUtil.readGbkString(msgBodyBuf, authCodeLen);
        //Terminal IMEI
        String imei = CommonUtil.readGbkString(msgBodyBuf, 15);
        //software version
        String softwareVersion = CommonUtil.readGbkString(msgBodyBuf, 20);

        TerminalAuthInfo terminalAuthInfo = new TerminalAuthInfo();
        terminalAuthInfo.setAuthCode(authCode);
        terminalAuthInfo.setImeiCode(imei);
        terminalAuthInfo.setSoftwareVersion(softwareVersion);
        return terminalAuthInfo;
    }
}
